package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@RequiredArgsConstructor
public class RefreshIntercepter implements HandlerInterceptor {

    @Resource
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("authorization");
        log.info("token:{}",token);
        if (StrUtil.isBlank(token)) {
            return true;
        }
        //从redis中获取用户
        HashOperations hashOperations = stringRedisTemplate.opsForHash();
        Map entries = hashOperations.entries(RedisConstants.LOGIN_USER_KEY + token);
        log.info("entries:{}",entries);
        //判断用户是否存在
        if (entries.isEmpty()) {
            return true;
        }
        //将Map转为UserDto
        UserDTO user = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);
        log.info("user:{}",user);
        //保存用户信息到ThreadLocal
        UserHolder.saveUser(user);
        //刷新用户信息有效期
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token, RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }

}
